var myExt_urlBarListener = {	
	QueryInterface: function(aIID){
		if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
       	    aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
       		aIID.equals(Components.interfaces.nsISupports))
     	return this;
   		throw Components.results.NS_NOINTERFACE;
  	},
  	onLocationChange: function(aProgress, aRequest, aURI){
    	urlChanger.processNewURL(aURI);
  	},
	onStateChange: function() {},
	onProgressChange: function() {},
	onStatusChange: function() {},
	onSecurityChange: function() {},
	onLinkIconAvailable: function() {}
};

var urlChanger_data = {
	oldURL: null,
	currentURL: null
};

var urlChanger = {
	
	init: function() {
    	// Listen for location change
    	gBrowser.addProgressListener(myExt_urlBarListener,
       		Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
       		
       	// Listen for tab close or select
       	var container = gBrowser.tabContainer;
		container.addEventListener("TabClose", this.tabRemoved, false);
		
		// Listen for page load
		document.getElementById("appcontent").addEventListener("DOMContentLoaded", this.onPageLoad, true);		
  	},
  
	uninit: function() {
		// remove all listeners
		gBrowser.removeProgressListener(myExt_urlBarListener);
		var container = gBrowser.tabContainer;
		container.removeEventListener("TabClose", this.tabRemoved, false);
		document.getElementById("appcontent").removeEventListener("DOMContentLoaded", this.onPageLoad, true);
	},

  	processNewURL: function(aURI) {
    	if (aURI.spec == urlChanger_data.currentURL) return;
    	urlChanger_data.oldURL = urlChanger_data.currentURL;
    	urlChanger_data.currentURL = aURI.spec;
    	alert("consultation paused of: "+urlChanger_data.oldURL+"\nNow consulting: "+urlChanger_data.currentURL);
  	},
  	
  	tabRemoved: function(event) {
		var browser = event.target.linkedBrowser;
		alert("(removing) send datas for: "+browser.currentURI.spec);
  	},

  	onPageLoad: function(aEvent) {
  		if(aEvent.originalTarget.nodeName == "#document"){
    		var doc = aEvent.originalTarget; // document that triggered "onload" event
    		var browser = gBrowser.getBrowserAtIndex(gBrowser.mTabContainer.selectedIndex);
    		if(browser.currentURI.spec == doc.location.href 
    			&& browser.currentURI.spec != "about:blank"){ // document loaded in the active tab
    			alert("(changing) send datas for: "+urlChanger_data.oldURL);
    		}
  		}    	
  	}
  	
};

window.addEventListener("load", function() {urlChanger.init()}, false);
window.addEventListener("unload", function() {urlChanger.uninit()}, false);
